<?php

namespace common\observer;

use common\model\ProjectModel;
use common\service\OrderService;
use common\service\StatusService;
use support\SingletonTrait;
use teamones\dbeventObserver\interfaces\SplObserver;
use teamones\dbeventObserver\interfaces\SplSubject;

/**
 * 外包任务完成 检查是否能进入结算状态
 */
class TaskDoneCheckOrderSettlementStatus implements SplObserver
{
    use SingletonTrait;

    /**
     * @inheritDoc
     */
    function update(SplSubject $subject): void
    {
        $updateData = $subject->getSplUpdateData();
        if (!isset($updateData['task_status'])) {
            return;
        }
        $task = $subject->getSubjectData();
        if ($task['step_type'] != 'step') {
            return;
        }
        if ($updateData['task_status'] != StatusService::getInstance()->getTaskDoneStatus()['id']) {
            return;
        }

        $project = model(ProjectModel::class)->find($task['project_id']);
        if (empty($project) || $project['type'] != ProjectModel::TYPE_OUTSOURCE) {
            return;
        }

        $orderService = OrderService::getInstance();
        $order = $orderService->getOrderByStepTaskId($task['id']);
        if (empty($order)) {
            trace('外包项目任务[' . $task['id'] . ']找不到关联的订单', "ERR");
            return;
        }
        if (!$orderService->checkOrderTaskListDoneStatus($order)) {
            APP_DEBUG && trace('订单[' . $order['id'] . ']任务没有全部完成', "DEBUG");
            return;
        }
        try {
            APP_DEBUG && trace("订单[" . $order['id'] . "]全部任务完成", "DEBUG");
            // 更新订单状态为待结算状态
            $orderService->markOrderWaitForSettlement($order);
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}
